package com.bnlr.lrparking.appui.search;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bnlr.lrparking.appui.carplace.CarPlaceDetailActivity;
import com.bnlr.lrparking.appui.login.VerificaActivity;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.like.LikeButton;
import com.like.OnLikeListener;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.adapter.HeaderAndFooterRecyclerViewAdapter;
import com.bnlr.lrparking.adapter.HorizontalAdapter;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.model.CarPlaceData;
import com.bnlr.lrparking.model.CarPlaceM;
import com.bnlr.lrparking.model.Location;
import com.bnlr.lrparking.widget.NativeDialog;
import com.bnlr.lrparking.constant.Params;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.shizhefei.view.indicator.Indicator;
import com.shizhefei.view.indicator.ScrollIndicatorView;
import com.shizhefei.view.indicator.slidebar.ColorBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;
import com.yolanda.nohttp.NoHttp;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 *
 * @author Administrator
 * @date 2017/6/5
 * 搜索车位
 */

public class SearchActivity extends BaseActivity  {

    @BindView(R.id.rely_search_back)
    RelativeLayout imgPerson;
    @BindView(R.id.et_title_search)
    EditText etTitleSearch;
    @BindView(R.id.rely_search_more)
    RelativeLayout imgMessage;
    @BindView(R.id.lv_search_list)
    RecyclerView lvSearchList;
    @BindView(R.id.rl_search_refresh)
    SwipeRefreshLayout rlSearchRefresh;
    @BindView(R.id.iv_hint)
    ImageView ivHint;
    @BindView(R.id.tv_hint_tips)
    TextView tvHintTips;
    @BindView(R.id.ll_hint)
    LinearLayout llHint;
    @BindView(R.id.img_deleteall)
    ImageView img_deleteall;
    List<CarPlaceData> searchList = new ArrayList<>();
    Double lat, lon;
    String keywords = "";
    String join = "";
    String edSearch="";
    @BindView(R.id.view_line)
    View viewLine;
    @BindView(R.id.img_search)
    ImageView imgSearch;
    private int defaultSelection = 0;
    private HorizontalAdapter horizontalAdapter;
    private ScrollIndicatorView scrollIndicatorView;
    private List<String> list = new ArrayList<>();
    private CarCommon carCommon=new CarCommon();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);

        llHint.setVisibility(View.GONE);
        lat = getIntent().getDoubleExtra("lat1", 0.0);
        lon = getIntent().getDoubleExtra("lon1", 0.0);
        getDatas();
        initView();
        etTitleSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                /*判断是否是 "DONE" 键*/
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {

                    /*隐藏软键盘*/
                    InputMethodManager imm = (InputMethodManager) v.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive())
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    if (!TextUtils.isEmpty(etTitleSearch.getText().toString())) {
                        keywords = etTitleSearch.getText().toString();
                        refrashData();
                    } else {
                        CommonUtil.showToask(baseContext, "请输入您要搜索的内容");
                    }
                    return true;
                }
                return false;
            }
        });
        etTitleSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(etTitleSearch.getText().toString())) {
                    keywords = "";
                    refrashData();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        imgSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(etTitleSearch.getText().toString())) {
                    keywords = etTitleSearch.getText().toString();
                    refrashData();
                } else {
                    CommonUtil.showToask(baseContext, "请输入您要搜索的内容");
                }
            }
        });



    }


    //输入框的监听
    private TextWatcher mTextWatcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            edSearch=etTitleSearch.getText().toString();
            if (!edSearch.equals("")){
                img_deleteall.setVisibility(View.VISIBLE);
                img_deleteall.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        etTitleSearch.setText("");
                    }
                });
            }else {
                img_deleteall.setVisibility(View.GONE);
            }

        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        refrashData();
    }

    private void refrashData() {
        footView.setVisibility(View.GONE);
        llHint.setVisibility(View.GONE);
        if (searchList.size() > 0) {
            searchList.clear();
            adapter.notifyDataSetChanged();
        }
        pageNum = 1;
        getDatas();
    }
    private View footView;
    private TextView tv_foot;
    SearchAdapter adapter;

    private void initView() {
        scrollIndicatorView=(ScrollIndicatorView)findViewById(R.id.singleTab_scrollIndicatorView);
        list.add("全部");
        list.add("免费停");
        list.add("洽谈中");
        list.add("已收藏");
        set(scrollIndicatorView,list);
        etTitleSearch.addTextChangedListener(mTextWatcher);
        footView = View.inflate(baseContext, R.layout.layout_footview, null);
        tv_foot = (TextView) footView.findViewById(R.id.tv_foot);
        footView.setVisibility(View.GONE);
        linearLayoutManager = new LinearLayoutManager(baseContext);
        lvSearchList.setLayoutManager(linearLayoutManager);
        lvSearchList.setItemAnimator(new DefaultItemAnimator());
        adapter = new SearchAdapter(baseContext, R.layout.item_search, searchList);
        headerAndFooterAdapter = new HeaderAndFooterRecyclerViewAdapter(adapter);
        headerAndFooterAdapter.addFooterView(footView);
        lvSearchList.setAdapter(headerAndFooterAdapter);
        rlSearchRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refrashData();
            }
        });

        lvSearchList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int total = linearLayoutManager.getItemCount();
                int lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                //lastVisibleItem >= totalItemCount - 4 表示剩下4个item自动加载，各位自由选择
                // dy > 0 表示向下滑动
                if (lastVisibleItem >= total - 2 && dy > 0) {
                    if (!isLoadingMore) {
                        isLoadingMore = true;
                        getDatas();
                    }
                }
            }
        });

        lvSearchList.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return rlSearchRefresh.isRefreshing();
            }
        });
    }


    public void getDatas() {
        try {
            if (CommonUtil.isNetworkAvailable(baseContext) == 0) {
                CommonUtil.showToask(baseContext, "当前无网络连接，请检查网络设置");
                return;
            }
            String uid = "0";
            if (!TextUtils.isEmpty(AppConfig.getInstance().getString("uid", ""))) {
                uid = AppConfig.getInstance().getString("uid", "");
            }

            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            if (type == 0) {
                mRequest.add("action", "GetParkByStr");
                mRequest.add("join", join);
            } else {
                mRequest.add("action", "GetParkByUser");
            }
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("s", keywords);
            mRequest.add("uid", uid);
            mRequest.add("lng", lon);
            mRequest.add("lat", lat);
            mRequest.add("index", pageNum);

            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomHttpListener<CarPlaceM>(this, true, CarPlaceM.class) {

                        @Override
                        public void doWork(CarPlaceM data, String code) {
                            if ("1".equals(code)) {
                                if (pageNum != 1) {
                                    if (data.getData().size() < 10) {
                                        footView.setVisibility(View.VISIBLE);
                                        tv_foot.setText(R.string.foot_all);

                                    } else {
                                        footView.setVisibility(View.VISIBLE);
                                        tv_foot.setText(R.string.foot_more);
                                    }
                                }
                                //加载更多
                                pageNum++;
                                searchList.addAll(data.getData());
                                adapter.notifyDataSetChanged();
                            }
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            rlSearchRefresh.setRefreshing(false);
                            isLoadingMore = false;
                            if (searchList.size() == 0) {
                                llHint.setVisibility(View.VISIBLE);
                                tvHintTips.setText("暂无数据哦~");
                                ivHint.setBackgroundResource(R.mipmap.nodata);
                            } else {
                                llHint.setVisibility(View.GONE);
                                if (!TextUtils.equals("1", code) && pageNum != 1) {
                                    footView.setVisibility(View.VISIBLE);
                                    tv_foot.setText(R.string.foot_all);
                                }
                            }
                        }
                    }, false);

        } catch (Exception e) {
        }
    }


    @Override
    public void doClick(View v) {
        super.doClick(v);
        switch (v.getId()) {
            case R.id.rely_search_back:
                finish();
                break;
        }
    }

    int type = 0;



    public class SearchAdapter extends CommonAdapter<CarPlaceData> {

        public SearchAdapter(Context context, int layoutId, List<CarPlaceData> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(ViewHolder holder, final CarPlaceData s, int position) {
            RelativeLayout lay_collect = holder.getView(R.id.lay_collect);
            LinearLayout lay_daohang = holder.getView(R.id.lay_daohang);
            LinearLayout lay_phone = holder.getView(R.id.lay_phone);
            LinearLayout lay_info = holder.getView(R.id.lay_carplace_info);

            final TextView tv_collect = holder.getView(R.id.tv_collect);
            final LikeButton likeButton = holder.getView(R.id.likeButton);
            holder.setText(R.id.tv_carplace_name, s.getName());
            if ("0".equals(s.getIsjoin())) {
                holder.setVisible(R.id.tv_mianfei, true);
                holder.setVisible(R.id.tv_car_kong, true);
                holder.setVisible(R.id.tv_jiamengzhong, false);
                holder.setVisible(R.id.rela_number_price, true);
                lay_info.setVisibility(View.VISIBLE);
                holder.setText(R.id.tv_car_kong, "开放时间：" + s.getOpentime());
                holder.setText(R.id.tv_car_number,s.getSellingcount() + "");
                holder.setText(R.id.tv_car_price,"车位价格："+s.getMaxsellingprice()+"万-"+s.getMinsellingprice()+"万");
            } else {
                holder.setVisible(R.id.rela_number_price, false);
                holder.setVisible(R.id.tv_mianfei, false);
                holder.setVisible(R.id.tv_car_kong, true);
                holder.setVisible(R.id.tv_jiamengzhong, true);
                holder.setText(R.id.tv_car_kong, "开放时间：全天24小时" );
                lay_info.setVisibility(View.GONE);
            }
            if ("0".equals(s.getIsFavorite())) {
                likeButton.setLiked(false);
                tv_collect.setTextColor(getResources().getColor(R.color.black_color));
            } else {
                likeButton.setLiked(true);
                tv_collect.setTextColor(getResources().getColor(R.color.main_color));
            }
            holder.setText(R.id.tv_car_juli, "" + s.getJuli());
            holder.setText(R.id.tv_car_xiaohao, "空车位：" + s.getChewei());
            holder.setText(R.id.tv_car_time, s.getSharevalue() + "共享值/小时");
//            TextView tv_car_xiaohao=holder.getView(R.id.tv_car_xiaohao);
//            String share ="消耗：" + s.getSharevalue() + "共享值/小时";
//            SpannableStringBuilder style = new SpannableStringBuilder(
//                    share);
//            style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.main_color)), 3,
//                    share.length(),
//                    Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
//            tv_car_xiaohao.setText(style);
//            holder.setText(R.id.tv_car_xiaohao, style.toString());

            String phone=s.getPhone();
            if(TextUtils.isEmpty(phone)){
                phone="暂无";
            }
            //holder.setText(R.id.tv_phone, "电话：" + phone);
            holder.setText(R.id.tv_address, "地址：" + s.getAddress());
            lay_daohang.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (AppConfig.getInstance().getBoolean("isLogin", false)) {
                        Location loc_now = new Location(Params.CurrentLat, Params.CurrentLon, "s");
                        Location loc_end = new Location(Double.valueOf(s.getLat()), Double.valueOf(s.getLng()), "e");
                        NativeDialog msgDialog = new NativeDialog(SearchActivity.this, loc_now, loc_end);
                        msgDialog.show();
                    }
                }
            });
            //拨打电话
            lay_phone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    carCommon.phoneDialog(baseContext);

                }
            });
            likeButton.setOnLikeListener(new OnLikeListener() {
                @Override
                public void liked(LikeButton likeButton) {
                        if (!AppConfig.getInstance().getBoolean("isLogin", false)) {
                            startActivity(VerificaActivity.class);
                            return;
                        }
                        SendCollect(s,true);
                        tv_collect.setTextColor(getResources().getColor(R.color.main_color));

                }

                @Override
                public void unLiked(LikeButton likeButton) {
                    if (!AppConfig.getInstance().getBoolean("isLogin", false)) {
                        startActivity(VerificaActivity.class);
                        return;
                    }
                        SendCollect(s,false);
                        tv_collect.setTextColor(getResources().getColor(R.color.black_color));

                }
            });
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(SearchActivity.this, CarPlaceDetailActivity.class);
                    intent.putExtra("lat", Double.valueOf(s.getLat()));
                    intent.putExtra("lon",Double.valueOf(s.getLng()));
                    intent.putExtra("CarPlace", s);
                    startActivity(intent);
                }
            });
        }
    }
    private void SendCollect(final CarPlaceData s, final boolean b) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "SetFavorite");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("parkId", s.getId());
            // 添加到请求队列
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<JSONObject>(baseContext, false, null) {
                        @Override
                        public void doWork(JSONObject data, String code) {
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                            try {
                                super.onFinally(obj, code, isSucceed);
                                if ("1".equals(code)) {
                                    if (b) {
                                        s.setIsFavorite("1");
                                    } else {
                                        s.setIsFavorite("0");
                                    }
                                    if (type == 1) {
                                        if (!b) {
                                            searchList.remove(s);
                                        }
                                    }
                                    adapter.notifyDataSetChanged();
                                } else {
                                    CommonUtil.showToask(baseContext, obj.getString("msg"));
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, false);
        } catch (Exception e) {

        }


    }


    /**
     * 横向listView
     */
    private void set(Indicator indicator, List list) {
        int Width=50;
        int selectColor = getResources().getColor(R.color.main_color);
        int unSelectColor = getResources().getColor(R.color.text_color);
        indicator.setAdapter(horizontalAdapter = new HorizontalAdapter(this, list));
        indicator.setScrollBar(new ColorBar(getApplicationContext(), selectColor, 4));
        float unSelectSize = 13;
        float selectSize = unSelectSize * 1f;
        indicator.getItemView(1).setMinimumWidth(30);
        indicator.setOnTransitionListener(new OnTransitionTextListener().setColor(selectColor, unSelectColor).setSize(selectSize, unSelectSize));
        indicator.setCurrentItem(defaultSelection, true);
        indicator.setOnItemSelectListener(new Indicator.OnItemSelectedListener() {
            @Override
            public void onItemSelected(View selectItemView, int select, int preSelect) {

                if (select==0){
                    type = 0;
                    join = "";
                    refrashData();
                }else if (select==1){
                    type = 0;
                    join = "0";
                    refrashData();
                }else if (select==2){
                    type = 0;
                    join = "1";
                    refrashData();
                }else if (select==3){
                    type = 1;
                    refrashData();
                }

            }
        });
    }

}
